/**
* Author: Samfu
* Time  : 下午9:47:28
* Desc  : 
*/
package com.fu.moneybag.utils;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

public class FileUploadProcessor {

	private Logger logger = Logger.getLogger(FileUploadProcessor.class);

	public String fileUpload(HttpServletRequest request, MultipartFile file, long id) {

		// 存储文件路径
		String fullPathFile = null;
		// 相对路径，用于图片显示
		String relatedPathFile = null;
		// 判断文件是否为空
		if (!file.isEmpty()) {
			try {
				// 文件保存路径
				String fullBasePath = request.getSession().getServletContext().getRealPath("/") + "avartar/" + id;
				File filepath = new File(fullBasePath);
				if (!filepath.exists()) {
					filepath.mkdirs();// 如果文件夹不存在则创建
				}
				fullPathFile = fullBasePath + "/" + file.getOriginalFilename();
				logger.info("存储路径： " + fullPathFile);
				// 转存文件
				file.transferTo(new File(fullPathFile));
				// 相对路径
				relatedPathFile = "avartar/" + id + "/" + file.getOriginalFilename();

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return relatedPathFile;
	}

	private static boolean validateFileType(MultipartFile file) {
		boolean support = false;
		String[] fileSupportSuffixes = { "jpg", "jpeg", "gif", "png" };
		String fileName = file.getOriginalFilename();
		String uploadFileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
		// 检查上传的文件是否符合类型
		for (int i = 0; i < fileSupportSuffixes.length; i++) {
			if (uploadFileSuffix.equals(fileSupportSuffixes[i])) {
				support = true;
			}
		}
		return support;
	}
}
